////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//   Software       :                                                         //
//   Layer          : SRC                                                     //
//   Package        :                                                         //
//   Component      :                                                         //
//                                                                            //
//   File           : cdatabase.cxx                                           //
//   Author         : RSO ( Rafael Sotomayor Brûlé )                          //
//   EMail          : rsotomayor@savtec.cl                                    //
//   Type           : C++ Source                                              //
//   Usage          :                                                         //
//   Purpose        : gestión de usuario                                      //
//                                                                            //
//                                                                            //
//   who when        what                                                     //
//   ~~~ ~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//   RSO 09-10-2010  Creation                                                 //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mylib/errlog.h"
#include "mylib/utilconf.h"

#include "cconfig.h"


CConfig::CConfig() {


}

CConfig::~CConfig() {

}


int CConfig::init(string dbname_p) {
  sqlite3    *dbConn;  

  dbconfig_a  = dbname_p ;

  if ( sqlite3_open(dbconfig_a.data(), &dbConn) != SQLITE_OK) {
    errLog::LOGERR((errLog::SEVERE,(char*) "connect: Can't open the database %s in the file system\n",dbconfig_a.data(),sqlite3_errmsg(dbConn)));
    return -1;
  }     

  int         rc ; 
  char        *zErrMsg = 0 ;
  string       sqlString; 

  string       sqlString_r[16];
  int          contador=0;

  sqlString = "CREATE TABLE IF NOT EXISTS  sac_config \
      ( \
      id              varchar(45),  \
      idseccion       varchar(45), \
      parametro       varchar(255), \
      PRIMARY KEY  (id,idseccion) \
      ); ";
  sqlString_r[contador++] =  sqlString ;

  for ( int i=0; i < contador ; i++) {
    sqlString = sqlString_r[i] ;
    rc = sqlite3_exec(dbConn,sqlString.data(), NULL, 0, &zErrMsg);
    if( rc!=SQLITE_OK ){
      errLog::LOGERR((errLog::SEVERE, (char *)"Connect SQL error: %s:[ %s ]\n", zErrMsg,sqlString.data()));
      sqlite3_free(zErrMsg);
      sqlite3_close(dbConn);     
      return -1;
    }     
  }

  sqlite3_close(dbConn);     
  return 0;
}


int CConfig::getParametro(string id_p,string idseccion_p,string &parametro_p) {
  int retcode=-1;

  int rc;
  sqlite3    *dbConn;    
  sqlite3_stmt *stmt;

  string sqlString ;

  sqlString   = "SELECT a.parametro  " ;
  sqlString  += "FROM sac_config a   " ;
  sqlString  += "WHERE " ;
  sqlString  += "a.id = '" + id_p + "'  " ;
  sqlString  += "AND a.idseccion = '" + idseccion_p + "'  " ;

  errLog::LOGERR((errLog::TRACE,"SQL: %s\n",sqlString.data()));

  if ( sqlite3_open(dbconfig_a.data(), &dbConn) != SQLITE_OK) {
    errLog::LOGERR((errLog::SEVERE,(char*) "connect: Can't open the database %s in the file system\n",dbconfig_a.data(),sqlite3_errmsg(dbConn)));
    sqlite3_close(dbConn);
    return -1 ;   
  }     

  rc = sqlite3_prepare(dbConn, sqlString.data(), -1, &stmt, 0);
  
  if ((rc = sqlite3_step(stmt)) != SQLITE_DONE) {
    switch(rc) {
      case SQLITE_BUSY:
        errLog::LOGERR((errLog::WARN,"busy, wait 1 seconds\n"));
        sleep(1);
        break;
      case SQLITE_ERROR:
        errLog::LOGERR((errLog::WARN,"step error: %s\n", sqlite3_errmsg(dbConn)));
        break;
      case SQLITE_ROW:
        const unsigned char *mydummy;
        mydummy                     = sqlite3_column_text(stmt,0);
        parametro_p                 = (mydummy != NULL ) ? (char *) mydummy : "" ;
        retcode = 0 ;
        break;
      default:
        errLog::LOGERR((errLog::WARN,(char *)"Error: %s\n", sqlite3_errmsg(dbConn)));
        break;
    }
  } else {
    errLog::LOGERR((errLog::WARN,(char *)"step error: %s\n", sqlite3_errmsg(dbConn)));
  }

  sqlite3_finalize(stmt);
  sqlite3_close(dbConn);

  return retcode;
}

int CConfig::readParametros() {
  int retcode = -1 ;
  string dummy;

  if ( getParametro("loglevel","global",dummy) == 0 ) {
    loglevel_a = atoi(dummy.data());
  } else {
    loglevel_a = 3 ;
  }


  if ( getParametro("idmodulo","global",dummy) == 0 ) {
    idmodulo_a = dummy;
  } else {
    idmodulo_a = "MODNA";
  }

  if ( getParametro("idmovil","global",dummy) == 0 ) {
    idmovil_a = dummy;
  } else {
    idmovil_a = "IMEIXXX";
  }

  if ( getParametro("port","server.socket",dummy) == 0 ) {
    portSocket_a = atoi(dummy.data());
  } else {
    portSocket_a = 12020 ;
  }

  if ( getParametro("address","server.socket",dummy) == 0 ) {
    addressSocket_a = dummy;
  } else {
    addressSocket_a = "127.0.0.1" ;
  }


  if ( getParametro("home","path",dummy) == 0 ) {
    pathHome_a = dummy;
  } else {
    pathHome_a = "/u/" ;
  }

  if ( getParametro("images","path",dummy) == 0 ) {
    pathImage_a = dummy;
  } else {
    pathImage_a = "/u/data/images/s100/" ;
  }

  if ( getParametro("maestros","database",dummy) == 0 ) {
    dbmaestros_a = dummy;
  } else {
    dbmaestros_a = "/u/data/sident_maestros.db" ;
  }

  if ( getParametro("hostname","server",dummy) == 0 ) {
    serverHostName_a = dummy;
  } else {
    serverHostName_a = "solem.rso.cl" ;
  }

  if ( getParametro("url","server",dummy) == 0 ) {
    serverUrl_a = dummy;
  } else {
    serverUrl_a = "/apps/src/s-caac/ws/wscaac.php" ;
  }

  if ( getParametro("urlupload","server",dummy) == 0 ) {
    serverUrlUpload_a = dummy;
  } else {
    serverUrlUpload_a = "/apps/src/s-caac/ws/upload.php" ;
  }


  if ( getParametro("address","server",dummy) == 0 ) {
    serverAddress_a = dummy;
  } else {
    serverAddress_a = "184.72.249.122" ;
  }

  if ( getParametro("port","server",dummy) == 0 ) {
    serverPort_a = atoi(dummy.data());
  } else {
    serverPort_a = 80 ;
  }


  if ( getParametro("enabled","server",dummy) == 0 ) {
    opcionSend2Server_a = atoi(dummy.data());
  } else {
    opcionSend2Server_a = 1 ;
  }


  if ( getParametro("timeoutconnect","server",dummy) == 0 ) {
     timeOutPostConnect_a = atoi(dummy.data());
  } else {
     timeOutPostConnect_a = 5 ;
  }

  if ( getParametro("timeoutretry","server",dummy) == 0 ) {
    timeOutPostRetry_a = atoi(dummy.data());
  } else {
    timeOutPostRetry_a = 30 ;
  }

  if ( getParametro("TZ","global",dummy) == 0 ) {
    gmtoffset_a = atoi(dummy.data());
  } else {
    gmtoffset_a = -4 ;
  }

  if ( getParametro("enabled","rfid",dummy) == 0 ) {
    rfidenabled_a = atoi(dummy.data());
  } else {
    rfidenabled_a = 1 ;
  }

  if ( getParametro("device","rfid",dummy) == 0 ) {
    rfiddevice_a = dummy;
  } else {
    rfiddevice_a   = "/dev/ttyUSB0" ;
  }


  if ( getParametro("ipaddress","network.eth0",dummy) == 0 ) {
    ethIpAddress_a = dummy;
  } else {
    ethIpAddress_a = "192.168.0.50" ;
  }

  if ( getParametro("gateway","network.eth0",dummy) == 0 ) {
    ethGateway_a = dummy;
  } else {
    ethGateway_a = "192.168.0.50" ;
  }

  if ( getParametro("mask","network.eth0",dummy) == 0 ) {
    ethMask_a = dummy;
  } else {
    ethMask_a = "255.255.255.0" ;
  }

  if ( getParametro("mask","network.eth0",dummy) == 0 ) {
    ethMask_a = dummy;
  } else {
    ethMask_a = "255.255.255.0" ;
  }

  if ( getParametro("dhcp","network.eth0",dummy) == 0 ) {
    ethDhcp_a = atoi(dummy.data());
  } else {
    ethDhcp_a = 0 ;
  }

  if ( getParametro("dns","network",dummy) == 0 ) {
    dns_a = dummy;
  } else {
    dns_a = "8.8.8.8" ;
  }


  if ( getParametro("dhcp","network.wlan",dummy) == 0 ) {
    wlanDhcp_a = atoi(dummy.data());
  } else {
    wlanDhcp_a = 0 ;
  }


  if ( getParametro("device","network.wlan",dummy) == 0 ) {
    wlanDevice_a = dummy;
  } else {
    wlanDevice_a   = "wlan0" ;
  }

  if ( getParametro("ssid","network.wlan",dummy) == 0 ) {
    wlanSSID_a = dummy;
  } else {
    wlanSSID_a   = "default" ;
  }

  if ( getParametro("key","network.wlan",dummy) == 0 ) {
    wlanKey_a   = dummy;
  } else {
    wlanKey_a   = "default" ;
  }


  if ( getParametro("wvdial","network.wvdial",dummy) == 0 ) {
    wvDial_a = dummy;
  } else {
    wvDial_a = "ENTEL" ;
  }

  if ( getParametro("enabled","scanner",dummy) == 0 ) {
    m300enabled_a = atoi(dummy.data());
  } else {
    m300enabled_a = 0;
  }

  if ( getParametro("enabled","geo",dummy) == 0 ) {
    geoenabled_a = atoi(dummy.data());
  } else {
    geoenabled_a = 0;
  }

  if ( getParametro("device","printer",dummy) == 0 ) {
    devicePrinter_a = dummy;
  } else {
    devicePrinter_a = "/dev/null" ;
  }

  retcode = 0 ;
  return retcode;
}

int CConfig::actualizaParametro(string id_p,string idseccion_p,string parametro_p) {
  int retcode=-1;

  int rc;
  sqlite3    *dbConn;    
  char        *zErrMsg = 0 ;

  string sqlString ;

  sqlString   = "UPDATE sac_config " ;
  sqlString  += "SET parametro='"+parametro_p+"' " ;
  sqlString  += "WHERE " ;
  sqlString  += "id = '" + id_p + "'  " ;
  sqlString  += "AND idseccion = '" + idseccion_p + "'  " ;

  errLog::LOGERR((errLog::TRACE,"SQL: %s\n",sqlString.data()));

  if ( sqlite3_open(dbconfig_a.data(), &dbConn) != SQLITE_OK) {
    errLog::LOGERR((errLog::SEVERE,"connect: Can't open the database %s in the file system\n",dbconfig_a.data(),sqlite3_errmsg(dbConn)));
    sqlite3_close(dbConn);
    return -1 ;   
  }     

  rc = sqlite3_exec(dbConn,sqlString.data(), NULL, 0, &zErrMsg);
  if( rc != SQLITE_OK ){
    errLog::LOGERR((errLog::SEVERE, "Connect SQL error: %s:[ %s ]\n", zErrMsg,sqlString.data()));
    sqlite3_free(zErrMsg);
    sqlite3_close(dbConn);     
    return -1;
  }     


  sqlite3_close(dbConn);

  return retcode;
}


int CConfig::ingresaParametro(string id_p,string idseccion_p,string parametro_p) {
  int retcode=-1;

  int rc;
  sqlite3    *dbConn;    
  char        *zErrMsg = 0 ;
  string sqlString ;


  sqlString   = "INSERT INTO sac_config(id,idseccion,parametro) " ;
  sqlString  += "VALUES  " ;
  sqlString  += "( " ;
  sqlString  += "'" + id_p + "', " ;
  sqlString  += "'" + idseccion_p + "', " ;
  sqlString  += "'" + parametro_p + "' " ;
  sqlString  += ");" ;

  errLog::LOGERR((errLog::TRACE,"SQL: %s\n",sqlString.data()));

  if ( sqlite3_open(dbconfig_a.data(), &dbConn) != SQLITE_OK) {
    errLog::LOGERR((errLog::SEVERE,"connect: Can't open the database %s in the file system\n",dbconfig_a.data(),sqlite3_errmsg(dbConn)));
    sqlite3_close(dbConn);
    return -1 ;   
  }     

  rc = sqlite3_exec(dbConn,sqlString.data(), NULL, 0, &zErrMsg);
  if( rc!=SQLITE_OK ){
    errLog::LOGERR((errLog::SEVERE,"Connect SQL error: %s:[ %s ]\n", zErrMsg,sqlString.data()));
    sqlite3_free(zErrMsg);
    sqlite3_close(dbConn);     
    return -1;
  }     

  sqlite3_close(dbConn);

  return retcode;
}


